const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const mysql = require('mysql2/promise'); // 使用mysql2的promise版本

// 创建数据库连接池
const pool = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'login',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 登录接口
router.post('/login', async (req, res) => {
    const { username, password } = req.body;

    // 1. 验证输入
    if (!username || !password) {
        return res.status(400).json({
            success: false,
            message: '用户名和密码不能为空'
        });
    }

    try {
        // 2. 从数据库查找用户
        const [rows] = await pool.query('SELECT * FROM login WHERE username = ?', [username]);

        if (rows.length === 0) {
            console.log('用户名错误');
            return res.status(401).json({
                success: false,
                message: '用户名或密码错误'
            });
        }

        const user = rows[0];

        // 3. 验证密码
        const isPasswordValid = bcrypt.compareSync(password, user.password);
        if (!isPasswordValid) {
            console.log('密码错误');
            return res.status(401).json({
                success: false,
                message: '用户名或密码错误'
            });
        }

        // 4. 生成 JWT token
        const token = jwt.sign({
            id: user.id,
            username: user.username
        }, 'your-secret-key', { expiresIn: '1h' });

        // 将token存入数据库
        await pool.query('UPDATE login SET token = ? WHERE username = ?', [token, user.username]);

        // 5. 返回成功响应
        res.json({
            success: true,
            message: '登录成功',
            data: {
                token,
                user: {
                    username: user.username
                }
            }
        });

    } catch (error) {
        console.error('数据库查询错误:', error);
        return res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});
// 获取个人信息接口
router.get('/user', async (req, res) => {
    const data = req.query;
    const username = data.username;
    try {
        const [rows] = await pool.query('SELECT * FROM login WHERE username = ?', [username]);
        res.json({
            success: true,
            message: '获取信息成功',
            data: {
                rows
            }
        });
    } catch (error) {
        console.error('数据库查询错误:', error);
        return res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
})

module.exports = router;